package com.framework.bdf4j.sysadm.vo;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.sysadm.entity.SysUser;

/**
 * <b>文件名： </b>SecurityUser.java<br/>
 * <b>类描述： </b>扩展Spring Security的用户类<br/>
 */
@SuppressWarnings("serial")
public class SecurityUser extends SysUser implements UserDetails{

	private Set<String> perms = null;
	private List<Integer> roles= null;
	private Set<Integer> menus = null;

    public SecurityUser(SysUser user ,UserInfo userinfo) {  
        if(user != null)  
        {  
            this.setUserId(user.getUserId()); 
            this.setPassword(user.getPassword());
            this.setDeptId(user.getDeptId());
            this.setUsername(user.getUsername());
            this.setTenantId(user.getTenantId());
        }   
        this.perms = new HashSet<String>(Arrays.asList(userinfo.getPermissions()));
        this.menus = new HashSet<Integer>(Arrays.asList(userinfo.getMenus()));
        this.roles = Arrays.asList(userinfo.getRoles());
    }

	@Override  
    public Collection<? extends GrantedAuthority> getAuthorities() {  
          
		if(CollectionUtils.isEmpty(perms)) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList("");
		}
		StringBuilder commaBuilder = new StringBuilder();
        for(String perm : perms){
            commaBuilder.append(perm).append(",");
        }
        String authorities = commaBuilder.substring(0,commaBuilder.length()-1);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities); 
    }

	/* 
	 * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
	 */
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	/* 
	 * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
	 */
	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	/* 
	 * @see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
	 */
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	/* 
	 * @see org.springframework.security.core.userdetails.UserDetails#isEnabled()
	 */
	@Override
	public boolean isEnabled() {
		if(!Constants.STATUS_NORMAL.equals(this.getDelFlag()))
			return true;
		else
			return false;
	} 
	
	public List<Integer> getRoles() {
        return roles;
    }

    public Set<Integer> getMenus() {
        return menus;
    }
}
